// 监听页面的停留时间
export function trackPageStay() {
    const needTracks = this.needTrack('pageStayTime')
    if (!needTracks.length) { return }
    let pageBeginTime = new Date().getTime()  // 记录页面开始停留时间
    let beforeTitle = document.title
    let beforePageUrl = location.href
    // 页面停留时间上报,停留1秒以上的,小于1秒的很多都是用来重定向的页面,上报来没意义
    const trackPageStaySend = () => {
        const pageEndTime = new Date().getTime()
        const stayTime = pageEndTime - pageBeginTime
        const obj = {
            describe: stayTime,
            pageTitle: beforeTitle,
            pageUrl: beforePageUrl
        }
        getConformTrack(obj.pageUrl).length && stayTime > 1000 ? this.sendDataBefore(needTracks, 'pageStayTime', obj) : ''  // 上报数据
        // 判断规则有没传url,如果没有url就直接上报就对了.如果url数组有就要判断一下
        pageBeginTime = new Date().getTime()
        beforeTitle = document.title
        beforePageUrl = location.href
    }
    const oldPushState = window.history.pushState
    window.history.pushState = function () {
        oldPushState.apply(this, arguments)
        trackPageStaySend()
    }
    const oldReplaceState = history.replaceState
    window.history.replaceState = function () {
        oldReplaceState.apply(this, arguments)
        trackPageStaySend()
    }
    // beforeunload: html页面销毁阶段,点击刷新按钮或者跳转到一个新项目会触发
    // popstate: back、go和forward触发这个事件
    const routerEvents = ['beforeunload', 'popstate']
    for (const item of routerEvents) {
        window.addEventListener(item, () => {
            trackPageStaySend()
        })
    }
    // 查看有没符合条件的对象
    function getConformTrack(needUrl) {
        // 先查地址,不传或者传空数组就是表示所有页面
        const needArr = needTracks.filter(itemA => {
            if (itemA.rule) {
                const urls = itemA.rule.urls
                if (!urls) {
                    return true
                } else {
                    const urlArr = urls.filter(item => { return needUrl === item })
                    return (urls && !urls.length) || urlArr.length
                }
            } else {
                return true
            }
        })
        return needArr
    }
}